#-*- encoding:utf-8 -*-
from sohu import DataSourceSohuImpl
import threading
import libxml2
from datasource import StockQuotation
import urllib2

class DataSourceW618Impl(DataSourceSohuImpl):
    url1 = "http://wap.618618.cn/stock/wap12/hangqing.jsp?code=%s&type=1"
    url2 = "http://wap.618618.cn/stock/wap12/hangqing.jsp?code=%s&type=2"    
    def get_stock_quotation(self,stock_code_list,func=None,user_data=None):
        if(func==None):
            if(len(stock_code_list)>1):return DataSourceSohuImpl.get_stock_quotation(self,stock_code_list)
            else:
                sq=self._get_stock_quotation_single_w(stock_code_list[0])
                return [sq]
        else:
            if(len(stock_code_list)>1):
                return DataSourceSohuImpl.get_stock_quotation(self,stock_code_list,func,user_data)
            else:
                sq=self._get_stock_quotation_single_w(stock_code_list[0])
                func([sq],*user_data)
    
    def _get_stock_quotation_single_w(self, code):
        url = DataSourceW618Impl.url1 % code[2:]
        tmp = self._get_(code, url)
        sq=StockQuotation(code)
        if not tmp==None:
            sq.name= tmp[0].split("(")[0]
            sq.time = tmp[1][-8:]
            sq.price_now=self._float(tmp[3])
            sq.price_highest=self._float(tmp[12])
            sq.price_lowest=self._float(tmp[13])
            sq.price_bid_buy=0.0
            sq.price_bid_sale=0.0
            sq.price_today_start=self._float(tmp[11])
            sq.price_lastday=self._float(tmp[10])
            sq.amount=self._float(tmp[8])*100
            sq.amount_money=self._float(tmp[9])*1000
            sq.change=self._float(tmp[5])
            sq.change_percent=self._float(tmp[6])
        return sq
                    
    def _float(self,line):
        return float(line.split("：")[1].replace("万", "").replace('%',''))

    def get_jy(self, stockid):
        url = DataSourceW618Impl.url2 % stockid
        tmp1 = self._get_(stockid, url)

        if not self.ret["error"]:
            for i in range(10):
                self.ret[self.cat2[i]] = {}
                self.ret[self.cat2[i]]["jiage"]= tmp1[3*i+4].split("：")[1]
                self.ret[self.cat2[i]]["xianshou"]= tmp1[3*i+5].split("：")[1]

    def _get_(self, stockid, url):
        handle = urllib2.urlopen(url)
        buf = handle.read()
        data = libxml2.parseMemory(buf, len(buf))

        for i in data.get_children():
            if i.name == "p":
                p = i

        tmp=[]
        for i in p.get_children():
            if i.name == "anchor":
                break
            if i.name == "text":
                line = i.content.replace("\n","").replace("\t","")
                if line != "":
                    tmp.append(line)

        if len(tmp) < 14:
            return None
        return tmp